import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import type { RootState } from './index'
import { StuAdd, EAddStatus } from '@/types/address/userAdd'
import { decode, encode } from 'js-base64'

interface AddressState {
  isEditor: boolean
  editorStdAdd: Partial<StuAdd> | undefined
  currendStdAdd: Partial<StuAdd> | undefined
  stdAddList: Array<StuAdd>
}
let state = {} as any
const idCode = localStorage.getItem('idAddress')
if (idCode != undefined && idCode != '') {
  state = { ...JSON.parse(decode(idCode)) }
}

const initialState: AddressState = {
  /**是否编辑状态 */
  isEditor: false,
  /**编辑后地址 */
  editorStdAdd: {},
  /**当前默认显示地址 */
  currendStdAdd: {},
  /**学生地址列表 */
  ...state,
  stdAddList: [],
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    setEditorStatus: (state, action: PayloadAction<boolean>) => {
      state.isEditor = action.payload
      if (!action.payload) {
        state.editorStdAdd = undefined
      }
      localStorage.setItem('idAddress', encode(JSON.stringify(state)))
    },
    setEditorStdAdd: (state, action: PayloadAction<StuAdd>) => {
      state.editorStdAdd = action.payload
      localStorage.setItem('idAddress', encode(JSON.stringify(state)))
    },
    setStdAddList: (state, action: PayloadAction<StuAdd[]>) => {
      state.stdAddList = action.payload
    },
    initCurrendStdAdd: (state, action: PayloadAction<StuAdd | ''>) => {
      // let currendStdAdd
      // const list = state.stdAddList.filter((val) => val.is_default === EAddStatus.Default)
      // if (list.length === 0 && state.stdAddList.length > 0) {
      //   currendStdAdd = state.stdAddList[0]
      // }
      // if (list.length > 0) {
      //   currendStdAdd = list[0]
      // }
      if (action.payload != '') {
        state.currendStdAdd = action.payload
        localStorage.setItem('idAddress', encode(JSON.stringify(state)))
      }
    },
    initstdAddList: (state, action: PayloadAction<StuAdd[]>) => {
      state.stdAddList = action.payload
      localStorage.setItem('idAddress', encode(JSON.stringify(state)))
    },
  },
})

export const {
  initCurrendStdAdd,
  initstdAddList,
  setEditorStdAdd,
  setEditorStatus,
  setStdAddList,
} = counterSlice.actions
export const selectCurrendStdAdd = (state: RootState) => state.address.currendStdAdd
//获取地址列表
export const selectStdAddList = (state: RootState) => state.address.stdAddList
//判断是否是编辑地址状态
export const selectIsEditor = (state: RootState) => state.address.isEditor
//编辑的地址
export const selectEditorStdAdd = (state: RootState) => state.address.editorStdAdd
export default counterSlice.reducer
